<?php


namespace app\api\controller;


use app\admin\model\product\Cart;
use app\admin\model\product\Lists;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\common\controller\Api;
use think\Controller;
use think\Db;
use think\Request;

class Productcart extends Api

{

    private static $model;

//    protected $noNeedLogin = '*';

    protected $noNeedRight = '*';


    public function __construct(Request $request = null)

    {

        parent::__construct($request);

        self::$model = new Cart();

    }


    /**
     * 购物车列表
     * @throws \think\exception\DbException
     */

    public function lists()

    {

        $pageSize = input('page_size', 15);


        $userId = $this->auth->id;

        $where = [

            'user_id' => $userId

        ];


        $list = self::$model->where($where)->order('createtime desc')->paginate($pageSize);

        if ($list) {

            foreach ($list as $val) {
                $val->lists->image = make_full_url($val->lists->image);

            }

        }

        $this->success('购物车', $list);

    }


    /**
     * 加入购物车
     */

    public function create()

    {

        $productId = input('product_id');

        $number = input('number');

        if (!$productId || !$number) {

            $this->error('参数缺失！');

        }


        $pInfo = Lists::find($productId);

        if (!$pInfo) {

            $this->error('该物资不存在！');

        }


        if ($pInfo->stock < $number) {

            $this->error('该物资库存不足！');

        }

        $userId = $this->auth->id;
        $cdata = [
            'user_id' => $userId,
            'product_id' => $productId,
        ];


        $row_info = self::$model->where($cdata)->find();

        if (!$row_info) {
            $cdata['number'] = $number;
            $ret = self::$model->create($cdata);
        } else {
            $ret = self::$model->where('id', $row_info->id)->setInc('number');
        }

        if (!$ret) {
            $this->error('加入失败！');
        }

        $this->success('加入成功！');

    }


    /**
     * 删除购物车商品
     */

    public function del()

    {

        $ids = input('ids');

        if (!$ids) {

            $this->error('参数缺失！');

        }


        $ids = trim($ids, ',');

        $ret = self::$model->where('id', 'in', $ids)->delete();

        if (!$ret) {

            $this->error('删除失败！');

        }


        $this->success('删除成功');

    }

}

